<?php

namespace App\Http\Controllers\Api\Room;

use App\Http\Controllers\Controller;
use App\Libs\Strategy\Context;
use App\Models\Members;
use App\Models\Members\MemberPipeline;
use App\Models\Rooms\RoomsGoodsBuy;
use Illuminate\Http\Request;

class HuibuyController extends Controller
{
    private $buy;

    public function __construct()
    {
        $this->buy = new Context(new RoomsGoodsBuy);
    }

    public function index(Request $request)
    {
        $goods = $this->buy->display($request->limit,function($query) use($request){
            $query->with('member');
            if($request->keyword)
            {
                $query->whereHas('member',function($query){
                $query->where('nickname','like','%'.request()->keyword.'%')->orWhere('mobile',request()->keyword);
                });
            }
            if($request->sale_type)
            {
               $query->where('sale_type',$request->sale_type);
            }
            if($request->status)
            {
               $query->where('status',$request->status);
            }
            if(isset($request->time[0]) && !empty($request->time[0])){
                $query->whereBetween('created_at',$request->time);
            }
            $query->whereIn('status',[4,5]);
            return $query;
        });
        return $this->success($goods);
    }


    public function show($id)
    {
        $buy = $this->buy->find($id);
        return $this->success([
            'buy' => $buy,
            'room_goods' => $buy->room_goods,
            'member' => $buy->member
        ]);
    }


    public function update(Request $request,$id){
        if(is_null($id))
        {
            return $this->error('操作失败');
        }
        $res = $this->buy->find($id);
         if($res->status == 5)
        {
            return $this->error('该回购已经完成，请不要重复操作');
        }
        if($res->sale_type == 1)
        {
            //金豆
            $bean = $res->buy_back_price * 10;
            $res->member->increment('bean',$bean);
            //加入流水
            MemberPipeline::MemberAddPipeline($res->member->id,$bean,17,'商品回购金豆充值+'.$bean,1,1);
            $res->status = 5;
            $res->action_at = now();
            $res->save();
        }else if($res->sale_type == 2)
        {
            //现金
            $res->status = 5;
            $res->action_at = now();
            $res->save();
        }else{
            return $this->error('该回购商品异常，请联系技术处理');
        }
        return $this->success(['message' => '操作成功']);
    }
}
